import AVFoundation

/// `AudioCapture` is a class that handles audio recording and processing.
public class AudioCapture {
    /// `audioEngine` is an instance of `AVAudioEngine` used for audio input and output.
    let audioEngine = AVAudioEngine()
    
    /// `deviceSampleRate` is a variable to store the actual sample rate of the audio device.
    private(set) var deviceSampleRate: Double = 0
    
    /// `setup` is a method that sets up the audio session for recording.
    private func setup() throws {
        let audioSession = AVAudioSession.sharedInstance()
        
        // 完全匹配 audio_streamer 的音频会话配置
        try audioSession.setCategory(.playAndRecord, options: .mixWithOthers)
        try audioSession.setActive(true)
        
        print("音频会话设置完成，匹配 audio_streamer 配置")
    }
    
    /// 请求麦克风权限
    public static func requestPermission(completion: @escaping (Bool) -> Void) {
        AVAudioSession.sharedInstance().requestRecordPermission { (granted) in
            completion(granted)
        }
    }
    
    /// `startSession` is a method that starts the audio capture session.
    /// - Parameters:
    ///   - bufferSize: The size of the audio buffer.
    ///   - sampleRate: The sample rate of the audio.
    ///   - cb: A callback that is called when audio data is captured.
    /// - Throws: An error if the audio session could not be set up.
    public func startSession(bufferSize: UInt32, sampleRate: Double, cb: @escaping ([Float]?, Double, Error?) -> Void) throws {
        try setup()
        
        let inputNode = audioEngine.inputNode
        let inputFormat = inputNode.inputFormat(forBus: 0)
        
        // 获取设备原生格式信息
        let actualSampleRate = inputFormat.sampleRate
        let channelCount = inputFormat.channelCount
        
        // 保存设备实际采样率
        self.deviceSampleRate = actualSampleRate
        
        print("📊 Device native format: \(actualSampleRate)Hz, \(channelCount) channels")
        
        // 设置音频格式 - 单声道
        let desiredFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: actualSampleRate, channels: 1, interleaved: false)
        
        // 直接在输入节点上安装tap，简化信号链
        inputNode.installTap(onBus: 0, bufferSize: bufferSize, format: desiredFormat) { [weak self] (buffer, time) in
            guard let self = self else { return }
            
            // 获取音频数据
            guard let channelData = buffer.floatChannelData else { return }
            let channelDataValue = channelData.pointee
            
            // 直接传递原始数据，不做任何处理
            let audioDataArray = stride(from: 0, to: Int(buffer.frameLength), by: 1).map{ channelDataValue[$0] }
            
            // 将数据传递给Flutter
            DispatchQueue.main.async {
                cb(audioDataArray, actualSampleRate, nil)
            }
        }
        
        do {
            // 启动音频引擎
            try audioEngine.start()
            print("🎙 Audio engine started successfully")
        } catch {
            print("❌ Failed to start audio engine: \(error)")
            cb(nil, 0, error)
        }
    }
    
    /// `stopSession` is a method that stops the audio capture session.
    public func stopSession() {
        // 移除tap并停止引擎
        audioEngine.inputNode.removeTap(onBus: 0)
        audioEngine.stop()
        
        do {
            try AVAudioSession.sharedInstance().setActive(false)
        } catch {
            print("Error deactivating audio session: \(error.localizedDescription)")
        }
        
        print("🛑 Audio engine stopped")
    }
}